<?php

class PagesController extends BaseController {
    
    public function viewHome()
    {
        return View::make('pages.home')->with('title', 'login');
    }

    public function doLogin()
    {
        if (Auth::attempt( array('email' => Input::get('email'), 'password' => Input::get('password')), true)) {
            return Redirect::to('/app');
        } else {
            Session::flash('error', 'incorrect email or password');
            return Redirect::back()->withInput();
        }
    }

    public function viewSignup() 
    {
        return View::make('pages.signup')->with('title', 'signup');
    }

    public function storeSignup() 
    {
        $validator = Validator::make(
            Input::all(),
            array (
                'email' => array ('email', 'required', 'unique:users'),
                'password' => array ('required', 'between:6,12'),
                'group' => array ('required', 'max:128')
            )
        );
        
        if ($validator->passes()) {
            // create the group            
            $group = Group::create(array('name'=>Input::get('group')));
            $group->save();

            // create the user
            $user = User::create(array (
                'email'=>Input::get('email'),
                'password'=>Hash::make(Input::get('password'))));

            $user->group_id = $group->id;
            $user->save();

            // go to app home
            Auth::logout();
            Auth::loginUsingId($user->id);
            Session::flash('welcome', 'Welcome to the Food Storage thing!');
            return Redirect::to('/app');
        } else {
            return Redirect::to('/signup')->withErrors($validator)->withInput();            
        }
    }    
}
